﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DevExpress.XtraEditors;

namespace SoufunData
{
    public partial class BUpdateImageForm : DevExpress.XtraEditors.XtraForm
    {
        
        private string _proName;
        private bool _hasAddNewImages;
        private bool _isUpdating;

        public BUpdateImageForm(string projectName)
        {
            InitializeComponent();
            _proName = projectName;
        }
         
        private void btn_addImages_Click(object sender, EventArgs e)
        {
            openFileDialog1.ShowDialog();
            string[]  files = openFileDialog1.FileNames;            
            foreach (string file in files)
            {
                if (File.Exists(file))
                { 
                    if (listView1.Items.Find(file, false).Length>0) 
                    {
                       XtraMessageBox.Show("您已选择了添加【" 
                           + file.Substring(file.LastIndexOf("\\")+1)+
                           "】,请不要重复添加同一图片！");
                        continue;
                    }
                    
                    Bitmap image = new Bitmap(file);
                    imageList1.Images.Add(image);
                    ListViewItem item = new ListViewItem();
                    item.Name = file;
                    item.Text = file.Substring(file.LastIndexOf("\\") + 1);
                    item.ImageIndex = imageList1.Images.Count - 1;
                    listView1.Items.Add(item);
                  
                }
                 
            }
        }

        private void btn_delete_Click(object sender, EventArgs e)
        {
            List<string> delList = new List<string>();
            foreach (ListViewItem item in listView1.SelectedItems)
            { 
                delList.Add(item.Name);
                listView1.Items.Remove(item);
            } 
        }

        private List<string> _imageList = new List<string>();

        private void btn_upLoad_Click(object sender, EventArgs e)
        {
            if (listView1.Items.Count==0)
            {
                XtraMessageBox.Show("您尚未选择需要添加的图片！");
                return;
            }
            _imageList.Clear();
            if (imgeCombo_imgType.SelectedIndex<0)
            {
                XtraMessageBox.Show("请选择上传图片所属图片分类！");
                return;
            }
            foreach (ListViewItem item in listView1.Items)
            {
                _imageList.Add(item.Name);
            }
            progressBarControl1.Properties.Maximum = _imageList.Count;
            progressBarControl1.Properties.Minimum = 0;
            progressBarControl1.Position = 0;
            progressBarControl1.Visible = true;
            btn_upLoad.Enabled = false;
            btn_addImages.Enabled = false;
            btn_delete.Enabled = false;
            imgeCombo_imgType.Enabled = false;
            Thread tUpload = new Thread(UpLoadImages) {IsBackground = true};
            tUpload.Start();
        }

        private void UpLoadImages()
        {
            try
            {
                string[] ftpConfig = ConfigClass.GetFtpConfig();
                FTPclient ftpClient = new FTPclient(ftpConfig[0], ftpConfig[1],
                    ftpConfig[2]);


                string rootPath = _proName + "/"

                     + imgeCombo_imgType.SelectedItem + "/";

                List<string> dirList = ftpClient.ListDirectory("");
                if (!dirList.Contains(_proName))
                {
                    ftpClient.FtpCreateDirectory(_proName);
                }
                List<string> imgDirList = ftpClient.ListDirectory("/" + _proName);
                if (!imgDirList.Contains(imgeCombo_imgType.SelectedItem.ToString()))
                {
                    ftpClient.FtpCreateDirectory(_proName + "/" +
                     imgeCombo_imgType.SelectedItem.ToString());
                }
                int failed = 0;
                //   string strImgList = "|";

                SqlClass sqlClass = new SqlClass();

                _isUpdating = true;
                foreach (string file in _imageList)
                {
                    string name = DateTime.Now.ToString("yyMMddHHmmss") +
                                  DateTime.Now.Millisecond.ToString("d4")
                                  + file.Substring(file.LastIndexOf("."));
                    string webPath = rootPath + name;
                    bool result = ftpClient.Upload(file, webPath);
                    if (result)
                    {
                        //  strImgList += name + "|";
                        BeginInvoke(new MethodInvoker(() =>
                        {
                            progressBarControl1.Position++;
                        }));
                        bool updateDb = sqlClass.UpdateImageList(_proName,
                        imgeCombo_imgType.Properties.Items[
                        imgeCombo_imgType.SelectedIndex].Value.ToString(),
                       "|" + name);
                        if (!updateDb)
                        {
                            XtraMessageBox.Show("请检测数据库连接是否正常！");
                            return;
                        }
                        _hasAddNewImages = true;
                    }
                    else
                    {
                        failed++;
                    }
                }

                _isUpdating = false;
                XtraMessageBox.Show("上传完毕，成功上传"
                    + (_imageList.Count - failed) + "张图片，失败" + failed + "张！");

                _imageList.Clear();
                BeginInvoke(new MethodInvoker(() =>
                {
                    progressBarControl1.Visible = false;
                    btn_upLoad.Enabled = true;
                    btn_addImages.Enabled = true;
                    btn_delete.Enabled = true;
                    imgeCombo_imgType.Enabled = true;
                    listView1.Items.Clear();
                }));
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
                BeginInvoke(new MethodInvoker(() =>
                {
                    progressBarControl1.Visible = false;
                    btn_upLoad.Enabled = true;
                    btn_addImages.Enabled = true;
                    btn_delete.Enabled = true;
                    imgeCombo_imgType.Enabled = true;
                   
                }));
            }
         
            
        }

        private void BUpdateImageForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_isUpdating)
            {
                if (XtraMessageBox.Show("正在上传图片，若关闭窗口，将取消上传，是否确定关闭！",
                    "警告：", MessageBoxButtons.YesNo)==DialogResult.No)
                {
                    e.Cancel = true;
                    return;
                }
                
            }
           this.DialogResult = _hasAddNewImages ? DialogResult.Yes : DialogResult.No;
        }

 
    }
}